import Cookie from 'js-cookie'

//本地缓存的适配打点-操作封装
function getOrSetLocalStorage(key, value, keys){//key,value:写入、keys删除
  var returnObj = {"nows": [], "logs": []};
  var localData = null;
  //get
	try{
		var storage = window.localStorage;
		if(storage){
			if(storage.getItem("nhd")){
				localData = storage.getItem("nhd");
			}
		}
	}catch(e){
		localData = null;
	}
  if(localData){
      localData = JSON.parse(localData);
      if(toString.call(localData) != "[object Object]") localData = {};
  }else{
      localData = {};
  }
  //追加
  if(key && value){
    localData[key] = value;
  }
  //delete
  if(keys){
    if(toString.call(keys) == "[object Array]"){
      for(var k=0; k<keys.length; k++){
        delete localData[keys[k]];
      }
    }
  }
  //set
  try{
    var storage = window.localStorage;
    if(storage){
      storage.setItem("nhd", JSON.stringify(localData));
    }
  }catch(e){
  }

  var returnSum = 0;
  for(var i in localData){
    if(localData[i]){
      if(returnSum < 50){
        returnObj.nows.push(i);
        returnObj.logs.push(localData[i]);
        returnSum = returnObj.nows.length;//每次上传不超过50个点
      }else{
        continue;
      }
    }
  }
  return returnObj;
}

export function heartPoint() {
  //每次路由，检测本地缓存是否有视频打点遗留数据，并选取最大50个点上报
  var lszobj = getOrSetLocalStorage(null, null, null);

  if (lszobj.nows.length > 0) {
    (function(nows, logs){
      $.ajax({
        type: 'POST',
        url: '/video-log/heartbeat/',
        timeout: 3000,
        // dataType: 'json',
        contentType: 'application/json',
        headers: {
          'xtbz': Cookie.get('platform_id') == 8 ? 'training' : 'cloud',
          'X-CSRFToken': Cookie.get("csrftoken")
        },
        data: JSON.stringify({ "heart_data": JSON.parse(logs) }),
        success: function (res) {
          getOrSetLocalStorage(null, null, JSON.parse(nows));
        },
        error: function (jqXHR, textStatus, errorThrown) {
          // console.log(arguments)
        }
      });
    })(JSON.stringify(lszobj.nows), JSON.stringify(lszobj.logs));
  }
}

// export function heartPoint() {
//   //在web端页面中添加此逻辑，用来提交localstorage中打点数据'nhd'给后端：
//   var localData = null;
//   try {
//     var storage = window.localStorage;
//     if (storage) {
//       if (storage.getItem("nhd")) {
//         localData = storage.getItem("nhd");
//       }
//     }
//   } catch (e) {
//     localData = null;
//   }
//   if (localData) {
//     localData = JSON.parse(localData);
//     if (toString.call(localData) != "[object Object]") localData = {};
//   } else {
//     localData = {};
//   }
//   var logs = [];
//   for (var i in localData) {
//     var _log = localData[i];
//     logs.push(_log);
//   }
//   if (logs.length > 0) {
//     $.ajax({
//       type: 'POST',
//       url: '/video-log/heartbeat/',
//       timeout: 3000,
//       // dataType: 'json',
//       contentType: 'application/json',
//       headers: {
//         'xtbz': Cookie.get('platform_id') == 8 ? 'training' : 'cloud',
//         'X-CSRFToken': Cookie.get("csrftoken")
//       },
//       data: JSON.stringify({ "heart_data": logs }),
//       success: function (res) {
//         try {
//           var storage = window.localStorage;
//           if (storage) {
//             storage.setItem("nhd", "{}");
//           }
//         } catch (e) {
//         }
//       },
//       error: function (jqXHR, textStatus, errorThrown) {
//         console.log(arguments)
//       }
//     });
//   }
// }